package juc.lock;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest {

    public static void main(String[] args) {

        //声明3个窗口 state:资源数
        Semaphore windows = new Semaphore(3);

        for (int i=0;i<5;i++){
            new Thread(()->{
                try {
                    //windows.acquire();
                    boolean b = windows.tryAcquire(1000, TimeUnit.MILLISECONDS);
                    if(b){
                        System.out.println(Thread.currentThread().getName()+":开始买票");
                        Thread.sleep(5000);
                        System.out.println(Thread.currentThread().getName()+":购票成功");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    windows.release();
                }
            }).start();
        }

    }

}
